var previewTimeout;

var noInteraction = false;

var selectedRowID;

function setUp(){
	
	PicBoard.getTranslations(['lang_321_confirmDeleteBook', 'lang_322_donateConfirm', 'lang_51_yes', 'lang_52_no'], function(){});
			
	$('#controlArea').css({
		'margin-top': '27px',
		'height': $('#UserResultArea').height() 
	});

	// Bind buttons
	
	// Select anywhere in the row and it'll select it.
	$('tr').bind('click', function(){
		$(this).find('input[type=radio]').attr('checked', 'checked');
	});
	
	
	// Buttons for move up/down
	$('button#moveUp').bind('click', function(){
		rowRadio = $('input[type=radio]:checked');
		
		if(rowRadio.length == 0){
			alert("Please select a row before attempting to reorder this book.");
		} else {
			// Is it possible to move up? If we're at the top we need to disallow this.
			if(rowRadio.attr('id') == $('input[type=radio]:first').attr('id')) {
				alert('You cannot move this item up as it is already at the top.');
				return;
			}
			
			// Disable the buttons while we process.
			disableControls();
			
			bID = window.location.toString().match(/id=(\d+).*?$/);
			
			chartID = rowRadio.parentsUntil('tr').parent().find('input[name=chartID]').val();
			bookID = bID[1];			
			
			$.post(PicBoard.baseURL + "rsrc.php?req=moveChartPositionBook", { bID: bookID, chID: chartID, direction: 'up' }, function(data){
				if(data.statusCode == 200){
					shiftRow(rowRadio.parentsUntil('tr').parent(), "up");
				} else {
					alert(data.message);
				}
				
				enableControls();
			}, 'json');
		
			
		}
		
	});
	
	$('button#moveDown').bind('click', function(){
		rowRadio = $('input[type=radio]:checked');
		
		if(rowRadio.length == 0){
			alert("Please select a row before attempting to reorder this book.");
		} else {
			if(rowRadio.attr('id') == $('input[type=radio]:last').attr('id')) {
				alert('You cannot move this item down as it is already at the bottom.');
				return;
			}
			// Is it possible to move down? If we're at the bottom we need to disallow this.

			// Disable the buttons while we process.
			disableControls();
			
			bID = window.location.toString().match(/id=(\d+).*?$/);
			
			chartID = rowRadio.parentsUntil('tr').parent().find('input[name=chartID]').val();
			bookID = bID[1];
			
			$.post(PicBoard.baseURL + "rsrc.php?req=moveChartPositionBook", { bID: bookID, chID: chartID, direction: 'down' }, function(data){
				if(data.statusCode == 200){
					shiftRow(rowRadio.parentsUntil('tr').parent(), "down");
				} else {
					alert(data.message);
				}
				
				enableControls();
			}, 'json');
		}
	});

	
	// Preview pane
	$('#UserResultArea').find('a.viewLink').bind('mouseover', function(e){
		thumbnail = $(this).children('input[name=thumb]').val();

		if(thumbnail != "" && $('#floatPreview').length == 0){
			floatDiv = $('<div>', { id: 'floatPreview', style: 'position:absolute; left:' + e.pageX + 'px; top:' + e.pageY + 'px; width:300px; height:300px' }).append($('<img>', { src: thumbnail }));
			$('body').append(floatDiv);
			
			clearTimeout(previewTimeout);
			
			if($('#floatPreview').children('img').height() > $('#floatPreview').children('img').width()){
				$('#floatPreview').children('img').css({ 'height':'300px', 'width':'auto' });
			} else {
				$('#floatPreview').children('img').css({ 'width':'300px', 'height':'auto' });
			}
		}
	});
	
	$('a.insertLink').bind('click', function(){

		selectedRowID = parseInt($(this).parentsUntil('tr').parent().find('td:first').text());

		bID = window.location.toString().match(/id=(\d+).*?$/);
		bookID = bID[1];
		
		getFragment('importChart', function(data){
			// Get the datasource
			$.post(PicBoard.baseURL + 'rsrc.php?req=getImportableCharts', { 'bookID': bookID }, function(data){
				$('select#importFrom').children().remove();
			
				for(i in data.payload){
					$('select#importFrom').append(
						$('<option>', { value: data.payload[i].chID, text: data.payload[i].name })
					);
				}
				
				$('select#importAt').children().remove();
				
				for(i=1; i <= data.chartPages;i++){
					$('select#importAt').append(
						$('<option>', { value: i, text: i })
					);
				}
				
				$('select#importAt').children('option:eq(' + (selectedRowID-1) + ')').attr('selected', 'selected');
				
			}, 'json');
			
			// Show the dialog
			jQuery.facebox(data);
			
			// Bind the insert button
			$('button#confirm_import').bind('click', function(){
				selectedID = $('select#importFrom').children('option:selected').val();
				
				$.post(PicBoard.baseURL + 'rsrc.php?req=addLinkChartBook', { 'bookID': bookID, 'chartID': selectedID, 'atID': $('select#importAt').val(), 'side': $('input[name=position]:checked').val() }, function(data){
					if(data.statusCode == 200){
						jQuery.facebox.close();
						location.reload(true);
					} else {
						alert(data.message);
					}
				}, 'json');
			});
		});
		

	});	
	
	$('a.removeLink').bind('click', function(){	
		// Remove the chart from this book.
			
			linkRef = this;
			
			bID = window.location.toString().match(/id=(\d+).*?$/);
			
			chartID = $(this).parentsUntil('tr').parent().find('input[name=chartID]').val();
			bookID = bID[1];
			
		$.post(PicBoard.baseURL + 'rsrc.php?req=removeChartLink', { 'bookID': bookID, 'chartID': chartID }, function(data){
			if(data.statusCode == 200){
				
				$(linkRef).parentsUntil('tr').parent().nextAll().children('td:first').each(function(i){
					val = parseInt($(this).text());
					$(this).text(val - 1);
				});
				
				$(linkRef).parentsUntil('tr').parent().remove();
			} else {
				alert(data.message);
			}
		}, 'json');	
	});
	
	$('#UserResultArea').find('a.viewLink').bind('mouseout', function(){
		if($('#floatPreview').length > 0) {
			previewTimeout = setTimeout(function(){ $('#floatPreview').remove(); }, 500);
		}
	});	
	
	
	$('#groupSelector').bind('change', function(){
		window.location = "bookeditor?id=" + $(this).val();
	});
	
}

function disableControls(){
	noInteraction = true;
	$('button').button('disable');
	$('input[type=radio]').attr('disabled', 'disabled');
	
	 showLoad();
}

function enableControls(){
	noInteraction = false;
	$('button').button('enable');
	$('input[type=radio]').removeAttr('disabled');
	
	 hideLoad();
}

function showLoad(){
	$('#loadIndicator').css('visibility', 'visible');
}

function hideLoad(){
	$('#loadIndicator').css('visibility', 'hidden');
}

// Move row up or down in the table
function shiftRow(row, direction){
	row = $(row);

	switch(direction){
	
		case "up":
			prevRow = row.prev();
			newPage = prevRow.children('td:first').text();
			row.insertBefore(prevRow);
			
			prevRow.children('td:first').text(parseInt(newPage) + 1);
			row.children('td:first').text(newPage);
		break;
	
	
		case "down":
			nextRow = row.next();
			newPage = nextRow.children('td:first').text();
			row.insertAfter(nextRow);
			
			nextRow.children('td:first').text(parseInt(newPage) - 1);
			row.children('td:first').text(newPage);
		break;
	
	}
}

PicBoard.addLoadEvent( "setUp()" );